/**
 * Progetto PRAISED.
 * 07/feb/2011
 */
package it.uniroma3.engine.util;

import it.uniroma3.engine.model.Token;
import it.uniroma3.engine.model.Tokenizer;

import java.util.List;
import java.util.Locale;

import com.ibm.icu.text.NumberFormat;
import com.ibm.icu.text.RuleBasedNumberFormat;

/**
 * NumbersFormatter : This class is responsible for managing spelled out the words with numbers
 * 
 * @author Accosta Augusto
 * @author Lopez Elisabetta
 *
 */
public class NumbersFormatter {

	/**
	 * no-args constructor
	 */
	public NumbersFormatter() {}
	
	/**
	 * This method substitutes numbers that occur in the text input with its spelled out value
	 * 
	 * @param text
	 * @return the new text
	 */
	public String substituteNumbersBySpelledOutNumbers(String text) {
		List<Token> tokenList = Tokenizer.getTokens(text);
		StringBuffer str = new StringBuffer();
		double number;
		
		for (Token token : tokenList) {
			number = findNumbers(token.getToken());
			
			if(number != 0d) {
				NumberFormat formatter = new RuleBasedNumberFormat(Locale.ENGLISH, RuleBasedNumberFormat.SPELLOUT);
				String result = formatter.format(number).replace("-", " ");
				
				token.setToken(token.getToken().replace(Integer.toString((int)number), " " + result));
				
			}
			str.append(token.getToken() + " ");
		}
		
		return str.toString().substring(0, str.lastIndexOf(" "));
	}
	
	/**
	 * This method extracts the number contained within the text input 
	 * 
	 * @param value
	 * @return the number
	 */
	private Double findNumbers(String value) {
		double number = 0d;
		StringBuffer strb = new StringBuffer();
		
		for (int i = 0; i < value.length(); i++) {
			if(Character.isDigit(value.charAt(i)))
				strb.append(value.charAt(i));
		}
		try {
			number = Double.parseDouble(strb.toString());
			
		} catch (Exception e) {
			return number;
		}
		
		return number;
	}

}
